import baseApi from './baseApi';
import { getMerchantId } from './merchantService';

// 地址信息
export interface Address {
  receiver: string;
  phone: string;
  address: string;
}

// 订单商品项
export interface TradeOrderItem {
  productId: number;
  productName: string;
  variantId?: number; // 商品规格ID
  variantName?: string; // 商品规格名称
  price?: number; // 在创建订单API中不需要发送
  quantity: number;
  amount?: number; // 在创建订单API中不需要发送
  remark?: string;
}

// 创建交易订单请求参数
export interface CreateTradeParams {
  uid?: number; // 用户ID，可选
  channel: string; // 渠道
  restaurantId: number; // 餐厅ID
  tableId: number; // 餐桌ID
  seat?: number; // 就餐人数
  address?: Address; // 地址信息，外卖需要
  deliveryType?: number; // 配送类型：1-堂食 2-外卖
  tradeOrderList: TradeOrderItem[]; // 订单商品列表
  remark?: string; // 备注
  isPrint?: boolean; // 是否打印
}

// 交易订单响应
export interface TradeResponse {
  id: number; // 交易ID
  tradeNo: string; // 交易单号
  createdAt: string; // 创建时间
  amount: number; // 订单总额
}

// 订单列表查询参数
export interface TradeListParams {
  status?: number; // 订单状态
  tableId?: number; // 餐桌ID
  no?: string; // 订单号
  page?: number; // 页码
  pageSize?: number; // 每页数量
  keyword?: string; // 关键词
  sortType?: string; // 排序字段
  sort?: string; // 排序方向
  timeField?: string; // 时间字段
  startTime?: string; // 开始时间
  endTime?: string; // 结束时间
}

// 用户信息
export interface User {
  id: number;
  uuid: string;
  username: string;
  mobile?: string;
  credit: number;
  balance: number;
  createdAt: string;
  updatedAt: string;
}

// 餐厅信息
export interface Restaurant {
  createdAt: string;
  updatedAt: string;
}

// 餐桌信息
export interface RestaurantTable {
  id: number;
  name: string;
  createdAt: string;
  updatedAt: string;
}

// 支付信息
export interface Payment {
  originAmount: number; // 原价
  amount: number; // 实付金额
  adjust: number; // 调整金额
  discount: number; // 折扣金额
  balance: number; // 余额支付
  credit: number; // 积分支付
  received: number; // 实收金额
}

// 订单项信息
export interface OrderItem {
  productId: number;
  productName: string;
  productImage: string;
  variantId: number;
  variantName: string;
  quantity: number;
  price: number;
  totalAmount: number;
}

// 订单信息
export interface Order {
  id: number;
  no: string;
  status: number;
  payment: Payment;
  item: OrderItem;
  createdAt: string;
  updatedAt: string;
}

// 交易详情信息
export interface Trade {
  id: number;
  user: User | null;
  no: string;
  deliveryType: number;
  channel: number;
  restaurant: Restaurant;
  restaurantTable: RestaurantTable;
  actualSeats: number;
  paymentStatus: number; // 支付状态：0-未支付 1-已支付
  status: number; // 订单状态：1-进行中 2-已完成
  payment: Payment;
  receiver: unknown[];
  orders: Order[];
  paymentRecords: unknown[];
  remark: string;
  payAt: string;
  createdAt: string;
  updatedAt: string;
}

// 分页信息
export interface Pagination {
  page: number;
  pageSize: number;
  total: number;
}

// 订单列表响应
export interface TradeListResponse {
  pagination: Pagination;
  list: Trade[];
}

// 修改订单请求参数
export interface ModifyTradeParams {
  id: number;
  tableId: number;
  tradeOrderList: {
    orderId: number;
    productId: number;
    variantId: number;
    quantity: number;
  }[];
  totalAmount: number;
}

// 支付方式
export interface PayMethod {
  id: string;
  name: string;
  status: number;
}

// 支付方式列表响应
export interface PayMethodsResponse {
  code: number;
  message: string;
  data: PayMethod[];
}

// 绑定用户请求参数
export interface BindUserParams {
  userId: number;
}

// 结账请求参数
export interface CheckoutParams {
  action: 'preview' | 'pay';
  useBalance: boolean;
  useCredit: boolean;
  payMethod: string;
}

// 结账预览响应
export interface CheckoutPreviewResponse {
  balanceDeduction: number;  // 余额抵扣金额
  creditDeduction: number;   // 积分抵扣金额
  totalDeduction: number;    // 总抵扣金额
  amount: number;            // 实付金额
  usedCredit: number;        // 使用的积分数量
  usedBalance: number;       // 使用的余额金额
}

// 结账响应
export interface CheckoutResponse {
  code: number;
  message: string;
  data: CheckoutPreviewResponse | null;
}

// 响应接口类型
export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T | null;
}

// 业务Token响应
export interface BizTokenResponse {
  token: string;
  expiredAt: number;
}

/**
 * 获取下单业务Token
 * @returns 业务Token响应
 */
const getBizToken = async (): Promise<ApiResponse<BizTokenResponse>> => {
  try {
    const response = await baseApi.get('/admin/bizToken',{
      params: { action: 'createOrder' }
    });
    return response.data;
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  } catch (error) {
    return {
      code: -1,
      message: '获取业务Token失败',
      data: null
    };
  }
};

/**
 * 获取支付业务Token
 * @returns 业务Token响应
 */
const getPayBizToken = async (): Promise<ApiResponse<BizTokenResponse>> => {
  try {
    const response = await baseApi.get('/admin/trade/bizToken', {
      params: { action: 'pay' }
    });
    return response.data;
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  } catch (error) {
    return {
      code: -1,
      message: '获取支付业务Token失败',
      data: null
    };
  }
};

// 订单服务
const tradeService = {
  /**
   * 获取下单业务Token
   * @returns 业务Token响应
   */
  getBizToken,

  /**
   * 创建交易订单
   * @param params 交易参数
   * @returns 交易响应
   */
  createTrade: async (params: CreateTradeParams): Promise<ApiResponse<TradeResponse>> => {
    try {
      // 确保有餐厅ID
      if (!params.restaurantId) {
        const merchantId = await getMerchantId();
        if (!merchantId) {
          return {
            code: -1,
            message: '未选择商户',
            data: null
          };
        }
        params.restaurantId = merchantId;
      }

      // 先获取业务Token
      const tokenResponse = await getBizToken();
      if (tokenResponse.code !== 0 || !tokenResponse.data) {
        return {
          code: -1,
          message: tokenResponse.message || '获取业务Token失败',
          data: null
        };
      }

      // 准备请求参数，移除不需要的字段
      const requestParams = {
        channel: params.channel,
        restaurantId: params.restaurantId,
        tableId: params.tableId,
        seat: params.seat,
        remark: params.remark,
        tradeOrderList: params.tradeOrderList.map(item => ({
          productId: item.productId,
          productName: item.productName,
          variantId: item.variantId,
          variantName: item.variantName,
          quantity: item.quantity
        }))
      };

      // 发送创建订单请求，带上业务Token
      const response = await baseApi.post('/admin/trade', requestParams, {
        headers: {
          'x-order-token': tokenResponse.data.token
        }
      });
      
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '创建订单失败',
        data: null
      };
    }
  },

  /**
   * 获取交易订单详情
   * @param tradeId 交易ID
   * @returns 交易详情
   */
  getTradeDetail: async (tradeId: number): Promise<ApiResponse<Trade>> => {
    try {
      const response = await baseApi.get(`/admin/trade/${tradeId}`);
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '获取订单详情失败',
        data: null
      };
    }
  },

  /**
   * 获取交易订单列表
   * @param params 查询参数
   * @returns 订单列表响应
   */
  getTradeList: async (params: TradeListParams = {}): Promise<ApiResponse<TradeListResponse>> => {
    try {
      const queryParams = {
        page: params.page || 1,
        pageSize: params.pageSize || 20,
        sortType: params.sortType || 'updatedAt',
        sort: params.sort || 'desc',
        ...params
      };

      const response = await baseApi.get('/admin/trade/list', {
        params: queryParams
      });
      
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '获取订单列表失败',
        data: null
      };
    }
  },

  /**
   * 修改交易订单
   * @param params 修改参数
   * @returns 修改结果
   */
  modifyTrade: async (params: ModifyTradeParams): Promise<ApiResponse<unknown>> => {
    try {
      const response = await baseApi.post(`/admin/trade/${params.id}/modify`, params);
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '修改订单失败',
        data: null
      };
    }
  },

  /**
   * 获取支付方式列表
   * @returns 支付方式列表
   */
  getPayMethods: async (): Promise<PayMethodsResponse> => {
    try {
      const response = await baseApi.get('/admin/payMethods');
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '获取支付方式失败',
        data: []
      };
    }
  },

  /**
   * 完成交易（结账）
   * @param tradeId 交易ID
   * @returns 操作结果
   */
  finishTrade: async (tradeId: number): Promise<ApiResponse<unknown>> => {
    try {
      const response = await baseApi.post(`/admin/trade/${tradeId}/finish`);
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '结账失败',
        data: null
      };
    }
  },

  /**
   * 取消交易（清台）
   * @param tradeId 交易ID
   * @returns 操作结果
   */
  cancelTrade: async (tradeId: number): Promise<ApiResponse<unknown>> => {
    try {
      const response = await baseApi.post(`/admin/trade/${tradeId}/cancel`);
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '清台失败',
        data: null
      };
    }
  },

  /**
   * 打印制作分单
   * @param tradeId 交易ID
   * @returns 操作结果
   */
  printTicket: async (tradeId: number): Promise<ApiResponse<unknown>> => {
    try {
      const response = await baseApi.post(`/admin/trade/${tradeId}/printTicket`);
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '打印制作分单失败',
        data: null
      };
    }
  },

  /**
   * 打印结账单
   * @param tradeId 交易ID
   * @returns 操作结果
   */
  printCashier: async (tradeId: number): Promise<ApiResponse<unknown>> => {
    try {
      const response = await baseApi.post(`/admin/trade/${tradeId}/printCashier`);
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '打印结账单失败',
        data: null
      };
    }
  },

  /**
   * 绑定用户到订单
   * @param tradeId 交易ID
   * @param params 绑定参数
   * @returns 操作结果
   */
  bindUser: async (tradeId: number, params: BindUserParams): Promise<ApiResponse<unknown>> => {
    try {
      const response = await baseApi.post(`/admin/trade/${tradeId}/bindUser`, params);
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '绑定用户失败',
        data: null
      };
    }
  },

  /**
   * 结账预览或支付
   * @param tradeId 交易ID
   * @param params 结账参数
   * @returns 结账结果
   */
  checkout: async (tradeId: number, params: CheckoutParams): Promise<CheckoutResponse> => {
    try {
      // 获取支付业务Token
      const tokenResponse = await getPayBizToken();
      if (tokenResponse.code !== 0 || !tokenResponse.data) {
        return {
          code: -1,
          message: tokenResponse.message || '获取支付业务Token失败',
          data: null
        };
      }
      console.log(tokenResponse.data.token);
      const response = await baseApi.post(`/admin/trade/${tradeId}/checkout`, params, {
        headers: {
          'x-order-token': tokenResponse.data.token
        }
      });
      return response.data;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      return {
        code: -1,
        message: '结账操作失败',
        data: null
      };
    }
  }
};

export default tradeService; 